import RPi.GPIO as GPIO
import smbus
import time

class PCF8591:
    def __init__(self,address,bus_id=1):
        self.bus = smbus.SMBus(bus_id)
        self.address = address
    
    def read(self,channel):
        # 写入控制码, 指定读取的通道
        if channel == 0:
            self.bus.write_byte(self.address,0x00)
        elif channel == 1:
            self.bus.write_byte(self.address,0x01)
        elif channel == 2:
            self.bus.write_byte(self.address,0x02)
        elif channel == 3:
            self.bus.write_byte(self.address,0x03)
        # 读取数据
        return self.bus.read_byte(self.address)
        
    def write(self,value):
        value = int(value)
        if value>255:
            value=255
        elif value < 0:
            value = 0
        self.bus.write_byte_data(self.address,0x40,value)


if __name__ == '__main__':
    pcf = PCF8591(0x48,1)
    while True:
        x = pcf.read(0)
        print(f'x={x}')
        pcf.write(x-60)
        time.sleep(0.5)